package work;

import javafx.util.Pair;
import work.config.Constant;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

public class MapFile {


    private static Map<Pair<String, String>, Map<String, String>> pairToMap;

    private static Map<String, Map<String, String>> nameToMap;

    private static Map<String, Map<String, String>> codeToMap;

    static {
        pairToMap = readMap();

        if (pairToMap == null) {
            throw new RuntimeException("无法处理Excel文件");
        }

        nameToMap = new HashMap<>();
        codeToMap = new HashMap<>();

        for (Pair<String, String> pair : pairToMap.keySet()) {
            Map<String, String> map = pairToMap.get(pair);
            codeToMap.put(pair.getKey(), map);
            nameToMap.put(pair.getValue(), map);
        }
    }


    public static Map<String, String> getByName(String name) {
        return nameToMap.get(name);
    }

    public static Map<String, String> getByCode(String code) {
        return codeToMap.get(code);
    }



    private static String read() {

        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File(Constant.work,"映射关系.txt")));

            String line;
            StringBuilder r = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                r.append(line).append("\n");
            }

            reader.close();

            return r.toString();
        } catch (Exception e) {
            return null;
        }

    }


    //创建映射关系
    private static Map<Pair<String, String>, Map<String, String>> readMap() {

        Map<Pair<String, String>, Map<String, String>> pairMapMap = new HashMap<>();
        String read = read();

        String[] split = read.split("\n\n\n");

        for (String s : split) {

            String[] strings = s.split("\n");


            String index = strings[0];

            String[] fl = index.split("\t");

            String code = fl[0];
            String name = fl[1];

            Pair<String, String> pair = new Pair<>(code, name);


            Map<String, String> map = new HashMap<>();

            for (int i = 1; i < strings.length; i++) {
                String[] sp = strings[i].split("\t");
                String c = sp[0];
                String n = sp[1];
                map.put(n, c);
            }


            map.remove("主键");
            map.remove("主数据统一编码");
            map.remove("主数据统一编码");

            pairMapMap.put(pair, map);

        }

        return pairMapMap;
    }


}
